/*
 * To help in writing this file:
 *
 * Brian:  Anyway, you will create a HelpTicketUpdate, and then call its
 * createMethod. Make sure you use try{} catch{} for sqlexception,
 * numberformatexception, etc
 * (look at some other pages)
 *
 * Brian:  You would say HelpTicketUpdate htu = new HelpTicketUpdate(),
 * use its setUserId, setTicketId, and setContents, then call htu.update()
 *
 * Brian:  Anyway, Evan & Tim, I remember now.
 * Tim needs to pass you the ID of the helpticket, you will then
 * need to get the help ticket. You create an update from its fields,
 * and you use text that tim's page posts to create the field.
 * Both of you will need to check if supportuserid is valid (>0) to
 * tell if the ticket has been accepted.
 *
 * Hey Evan did you remember to call authenticateUser ?
 */

package helpdesk;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

/**
 * UpdateTicketServlet relays ticket updates to the database.
 *
 *
 * @author evan
 */
public class UpdateTicketServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
    throws ServletException, IOException {
        User user;            // User currently viewing the page, part of
                              // session.
        HelpTicket ticket;
        String ticketIdStr;   // ID of ticket that user requested to see.
        int ticketId = -1;         // Integer version of the ticket ID.
        HelpTicketUpdate htu;
        String htuContents;   // The contents or description
                              // of the ticket update.
        String closeMessage = "";
        RequestDispatcher rd; // For transferring control to a JSP page.
        String error="";      // String used to allow the JSP page to display an
                              // error message.

        boolean success = false;

        try {
            // Ensure the user is authenticated, storing its value in
            // variable user.
            if ((user=HelpdeskUtil.authenticateUser(request, response)) != null)
            {
                // Get ticket ID and update contents parameters for the
                // ticket update being created.
                ticketIdStr = request.getParameter("ticketId");
                htuContents = request.getParameter("contents");

                try
                {

                    // Parameters are always given as strings, so convert.
                    ticketId = Integer.parseInt(ticketIdStr);
                    ticket = HelpTicket.getById(ticketId);

                    // If there is no support user and we did not create the ticket,
                    // assign us. Make sure the user is a support user
                    if (user.getSupport() && ticket.getSupportUserId() <= 0 && user.getId()!=ticket.getUserId())
                    {
                        ticket.setSupportUserId(user.getId());
                    }

                    // Only allow the update if user is owner or assigned
                    // support and the ticket is open.
                    if ((ticket.getUserId()==user.getId() || ticket.getSupportUserId()==user.getId())
                         && ticket.getDateClosed() == null) {
                        // Instantiate the ticket update and create it in
                        // the database.
                        htu = new HelpTicketUpdate();
                        htu.setUserId(user.getId());
                        htu.setTicketId(ticketId);
                        if (request.getParameter("closed") != null) {
                            ticket.close();
                            closeMessage = "(Ticket closed)\n";
                        }
                        htu.setContents(closeMessage + htuContents);
                        htu.setVisible(true);           // Is this necessary?
                        htu.create();
                        response.sendRedirect("ticketdetails.jsp?ticketid=" + ticketId);
                        success = true;

                        // send email
                        if (ticket.getSupportUserId() > 0 && htu.getUserId() == ticket.getSupportUserId())
                        // user update, send email to support user
                        {
                            HelpdeskUtil.sendEmail(ticket.getUser(),
                                    "Your ticket has been updated", "Your ticket, "
                                    + ticket.getTitle() + ", has been updated " +
                                    "by a support user.");
                        }
                        else if (ticket.getSupportUserId() > 0) // support user updated, email regular user
                        {
                            HelpdeskUtil.sendEmail(ticket.getSupportUser(), "User's ticket updated",
                                    "A ticket you have accepted, " + ticket.getTitle() + ", has been updated by its " +
                                    "owner.");
                        }
                    }
                    else
                    {
                        error = "Failed to update ticket. Either you are not the owner " +
                                "or assigned support user of the ticket, or you " +
                                "are not a support user, or the ticket has already " +
                                "been closed.";
                        success = false;
                    }
                }
                catch (NumberFormatException ex)
                {
                    error = "Invalid ticket id";
                }
                catch (SQLException ex)
                {
                    error = "SQL error " + ex.getMessage();
                }

                // Display the JSP page.
                if (!success)
                {
                    request.setAttribute("error", error);
                    request.setAttribute("ticketId", new Integer(ticketId));
                    rd = request.getRequestDispatcher("/WEB-INF/updateticket.jsp");
                    rd.forward(request, response);
                }
            }


        } finally { }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}